/**
 * @Title: ProductSaleController.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年5月22日
 */
package com.fortune.rainshine.service.controller;

import java.util.List;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fortune.rainshine.common.BaseController;
import com.fortune.rainshine.common.utils.StringUtil;
import com.fortune.rainshine.service.service.ProductSaleService;
import com.fortune.rainshine.service.service.StockService;
import com.fortune.rainshine.system.service.CustomerService;
import com.fortune.rainshine.system.service.RedisService;
import com.fortune.rainshine.system.service.SmsSendFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.SmsParamsModel;
import com.fortune.rainshinecommon.model.service.StockRecordsModel;
import com.fortune.rainshinecommon.model.system.CustomerCardModel;
import com.fortune.rainshinecommon.util.RandomNumUtil;
import com.google.gson.Gson;

/**
 * @ClassName: ProductSaleController
 * @Description: TODO(店铺产品处理 - - 产品销售以及产品领用)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年5月22日
 *
 */
@Controller
@RequestMapping("/service/productSale")
@MultipartConfig
public class ProductSaleController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ProductSaleController.class);
    @Autowired
    private ProductSaleService service;
    @Autowired
    private StockService stockService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisService redisFeign;
    @Autowired
    private SmsSendFeign smsSendFeign;
    @Value("${smsSend.number}")
    private Integer number;


    @RequiresPermissions("productSale:view")
    @RequestMapping()
    public String product(Model model, HttpServletRequest request) {
        //获取当前商铺id
    	String parm = request.getHeader("Pass-Check-Session");
    	String parm2 = request.getHeader("Pass-Check-Session").substring(16, parm.length());
    	String shopId = parm2.substring(0,parm2.length()-9);
        //根据店铺id获取该店库存详情
        Object stocks = stockService.getStocksForShopSale(shopId).getData();
        model.addAttribute("stocks", stocks);
        return "productSale/productSaleList.html";
    }

    @RequiresPermissions("productSale:list")
    @RequestMapping("/list")
    public String addUser(Model model) {
        return "productSale/productSale_list.html";
    }

    @RequiresPermissions("productSale:sale")
    @RequestMapping("/sale")
    public String sale(Integer shopId,String orderList,Model model) {
        ParmsModel parm = new ParmsModel(0, 999, null, null, shopId);
        List<CustomerModel> customers = (List<CustomerModel>) customerService.listActive(parm).getData();
        model.addAttribute("customers", customers);
        model.addAttribute("orderList", orderList);
        return "productSale/productSale_sale.html";
    }


    @RequiresPermissions("productSale:add")
    @ResponseBody
    @RequestMapping("/add")
    public MsgModel add(@RequestBody StockRecordsModel model) {
        try {
            //判断用户是否存在
//            CustomerModel customer = customerService.getCustomerById(Integer.valueOf(model.getCustomerName()));
            CustomerModel customer = customerService.getCustomerById(model.getCustomerId());
            if (customer != null) {
                //redis key
                String key = RedisConstantEnum.BUYPRODUCT.getMessage() + customer.getCustomerPhone();
                //判断是否存在于redis中
                Boolean exists = redisFeign.exists(key);
                if (exists) {
                    //获取redis中的keyc
                    String sms = (String) redisFeign.get(key).getData();
                    if (sms.equals(model.getVerificationCode())) {
//                        model.setUser(this.getLoginUser());
                        model.setUserId(this.getLoginUserId());
                        MsgModel msg = service.add(model);
                        redisFeign.delete(key);
                        return msg;
                    } else {
                        return new MsgModel("验证码不正确", ResultCode.FAILURE);
                    }
                } else {
                    return new MsgModel("验证码不存在或者已过期", ResultCode.FAILURE);
                }
            } else {
                return new MsgModel("用户不存在", ResultCode.FAILURE);
            }
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("add ======> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }

    }

    @RequiresPermissions("productSale:use")
    @ResponseBody
    @RequestMapping("/use")
    public MsgModel use(@RequestBody StockRecordsModel model) {
        try {
//            model.setUser(this.getLoginUser());
            model.setUserId(this.getLoginUserId());
            model.setCreateId(this.getLoginUser().getUserId());
            return service.add(model);
        } catch (Exception e) {
            logger.error("use ======> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    /**
     * @Title: list
     * @Description: 销售stores_records列表
     * @author zhangxin
     * @date 2019年3月26日
     */
    @RequiresPermissions("productSale:view")
    @ResponseBody
    @GetMapping("/list")
    public MsgModel list(Integer page, Integer limit, String searchKey, String searchValue, Integer shopId, Integer type) {
        try {
            if (page == null) {
                page = 0;
                limit = 0;
            }
            if (StringUtil.isBlank(searchValue)) {
                searchKey = null;
            }
            ParmsModel parm = new ParmsModel(page, limit, searchKey, searchValue);
            parm.setShopId(shopId);
            parm.setType(type);

            return service.list(parm);
        } catch (Exception e) {
            logger.error("list =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }

    }

    /**
     * @Title: sms
     * @Description: 购买产品时获取验证码
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年5月21日
     */
    @RequiresPermissions("productSale:sms")
    @ResponseBody
    @RequestMapping("/sms")
    public MsgModel sms(@RequestBody CustomerCardModel customerCard) {
        try {
            CustomerModel customer = customerService.getCustomerById(customerCard.getCustomerId());
            String phone = customer.getCustomerPhone();
            Boolean exists = redisFeign.exists(RedisConstantEnum.BUYPRODUCT.getMessage() + phone);
            Boolean bo = false;
            if (exists) {
                redisFeign.delete(RedisConstantEnum.BUYPRODUCT.getMessage() + phone);
            }
            Gson gson = new Gson();
            String code = RandomNumUtil.getRandNum(number);
            SmsParamsModel smsParams = new SmsParamsModel();
            smsParams.setCode(code);
            String jsonParams = gson.toJson(smsParams);

            bo = smsSendFeign.sendSms(phone, jsonParams);
            if (bo) {
                redisFeign.set(RedisConstantEnum.BUYPRODUCT.getMessage() + phone, code, 60000);
            }
            return new MsgModel(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("sms ======> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }
}
